package com.demo.application.service;

import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.demo.application.dao.StockRepository;
import com.demo.application.entity.StockEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * Author: kosam
 */
@Service
public class StockService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private StockRepository stockRepository;

    @LcnTransaction //分布式事务注解
    @Transactional
    public String inventoryReduction(Long commodityId) {
        if (commodityId == null) {
            return "商品id不能为空!";
        }
        // 1.查询该商品id 是否存在
        StockEntity stockEntity = stockRepository.findByCommodityId(commodityId);
        if (stockEntity == null) {
            return "商品id不存在!";
        }
        // 2.判断商品是否有超卖
        if (stockEntity.getStock() <= 0) {
            return "当前商品已经买完啦!";
        }
        // 3.减去库存1
        stockEntity.setStock(stockEntity.getStock()-1);
       stockRepository.save(stockEntity);

        return "update stock success!";
    }
}
